<template>
	<view class="container">
		<view v-if="checkPermi(['puyu:lesson:add'])">
			<button class="uni-button" style="color:#ffffff;backgroundColor:#993399;borderColor:#993399 width: 100%;"
				type="primary" @click="handleAddLesson">添加课时</button>
		</view>
		<view class="query-form">
			<view class="query-item">
			<uni-data-select v-model="queryParams.coachId" :localdata="coachRange"
				placeholder="请选择教练"></uni-data-select>
			</view>
			<view class="query-item">
			<uni-data-select v-model="queryParams.stadiumId" :localdata="stadiumRange"
				placeholder="请选择场馆"></uni-data-select>
			</view>
			<view class="query-item">
			<uni-data-select v-model="queryParams.classesId" :localdata="classesRange"
				placeholder="请选择班次"></uni-data-select>
			</view>
			<view class="query-item">
			<button class="uni-button" size="mini" type="primary" @click="handleQuery">搜索</button>
			</view>
		</view>
		<uni-table ref="table" :loading="loading" border stripe emptyText="暂无更多数据">
			<uni-tr>
				<uni-th align="center">日期/教练/场馆/班次/备注</uni-th>
				<uni-th width="180rpx" align="center">操作</uni-th>
			</uni-tr>
			<uni-tr v-for="(item, index) in lessonList" :key="index">
				<uni-td>
					<view class="name">{{ parseTime(item.createTime, '{y}-{m}-{d}') }}</view>
					<view class="name">{{ getCoachName(item.coachId) }}</view>
					<view class="name">{{ getStadiumName(item.stadiumId) }}</view>
					<view class="name">{{ getClassesName(item.classesId) }}</view>
					<view class="name">学生总数：{{ item.puyuLessonStudents.length }}</view>
					<view class="name remark">{{ item.remark }}</view>
				</uni-td>
				<uni-td align="center">
					<view v-if="checkEditLesson(item)">
						<button class="uni-button" size="mini" type="primary"
							@click="handleEditLesson(item)">修改</button>
					</view>
					<view v-if="checkPermi(['puyu:lesson:rollcall'])">
						<!-- <button class="btn-rollcall" size="mini" type="default">点名</button> -->
						<button class="uni-button" size="mini" @click="handleLessonStudent(item)"
							style="color:#ffffff;backgroundColor:#993399;borderColor:#993399; height: 80rpx; padding: 10rpx 40rpx;">点名</button>
					</view>
					<view v-if="checkPermi(['puyu:lesson:remove'])">
						<button class="uni-button" size="mini" type="warn" @click="handleDeleteLesson(item)">删除</button>
					</view>
				</uni-td>
			</uni-tr>
		</uni-table>
		<uni-pagination :page-size="queryParams.pageSize" :current="queryParams.pageNum" :total="total" @change="change"
			prev-text="前一页" next-text="后一页" />
		<view class="page-sum">
			<text>当前页：{{ queryParams.pageNum }}，数据总量：{{ total }} 条，每页数据：{{ queryParams.pageSize }} 条</text>
		</view>
	</view>
</template>

<script>
	import {
		checkPermi,
		checkRole
	} from "@/utils/permission";
	import {
		listLesson,
		getLesson,
		delLesson,
		addLesson,
		updateLesson
	} from "@/api/puyu/lesson";
	import {
		listAllCoachs
	} from "@/api/puyu/coach";
	import {
		getDicts
	} from "@/api/system/dict/data";
	import { parseTime } from '@/utils/common';
	export default {
		data() {
			return {
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 课时表格数据
				lessonList: [],
				// 教练数据
				coachList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 5,
					deptId: null,
					coachId: null,
					stadiumId: null,
					classesId: null,
				},
				// 表单参数
				form: {},
				// 表单校验
				rules: {},
				puyuClassesOptions: [],
				puyuStadiumOptions: [],
			}
		},
		computed: {
			coachRange() {
				if (!this.coachList) {
					return [];
				}
				let arr = [];
				this.coachList.map(item => {
					let obj = {
						text: item.coachName,
						value: item.coachId,
					}
					arr.push(obj);
				});
				return arr;
			},
			stadiumRange() {
				if (!this.puyuStadiumOptions) {
					return [];
				}
				let arr = [];
				this.puyuStadiumOptions.map(item => {
					let obj = {
						text: item.dictLabel,
						value: item.dictValue,
					}
					arr.push(obj);
				});
				return arr;
			},
			classesRange() {
				if (!this.puyuClassesOptions) {
					return [];
				}
				let arr = [];
				this.puyuClassesOptions.map(item => {
					let obj = {
						text: item.dictLabel,
						value: item.dictValue,
					}
					arr.push(obj);
				});
				return arr;
			},
		},
		created() {
			this.getList();
			this.getCoachList();
		},
		onLoad() {
			// this.selectedIndexs = []
			// this.getData(1)
		},
		onShow() {
			this.getList();
		},
		methods: {
			checkPermi,
			checkRole,
			parseTime,
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 新增 */
			handleAddLesson() {
				this.$tab.navigateTo('/pages/puyu/lesson/add-lesson')
			},
			/** 编辑 */
			handleEditLesson(item) {
				this.$tab.navigateTo('/pages/puyu/lesson/edit-lesson?item=' + encodeURIComponent(JSON.stringify(item)));
			},
			/** 计算两个时间差几小时 */
			hoursBetween(time1, time2) {
				// 将时间字符串转换为Date对象
				  const date1 = new Date(time1);
				  const date2 = new Date(time2);				 
				  // 计算两个时间的时间戳差值
				  const diff = Math.abs(date2.getTime() - date1.getTime());				 
				  // 将差值转换为小时
				  const hours = diff / (1000 * 60 * 60);
				  // 返回结果
				  return hours;
			},
			/** 校验是否显示修改按钮 */
			checkEditLesson(item) {
				if (this.$auth.hasRole("manager")) {
					return true;
				}
				let hours = this.hoursBetween(parseTime(item.createTime, '{y}-{m}-{d} {h}:{i}:{s}'), parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'));
				return this.$auth.hasPermi("puyu:lesson:edit") &&  hours <= 3 ;
			},
			/** 点名 */
			handleLessonStudent(item) {
				item.coachName = this.getCoachName(item.coachId);
				item.stadiumName = this.getStadiumName(item.stadiumId);
				item.classesName = this.getClassesName(item.classesId);
				this.$tab.navigateTo('/pages/puyu/lesson/lesson-student?item=' + encodeURIComponent(JSON.stringify(item)));
			},
			/** 删除 */
			handleDeleteLesson(item) {
				const lessonIds = item.lessonId;
				this.$modal.confirm('是否确认删除课时编号为"' + lessonIds + '"的数据项？').then(function() {
				  return delLesson(lessonIds);
				}).then(() => {
				  this.getList();
				  this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			/** 查询课时列表 */
			getList() {
				this.loading = true;
				this.queryParams.orderByColumn = 'lessonId'; //查询字段是表格中字段名字
				this.queryParams.isAsc = 'descending'; //动态取值排序顺序
				listLesson(this.queryParams).then(response => {
					this.lessonList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			/** 查询教练用户列表 */
			getCoachList() {
				listAllCoachs().then(response => {
					this.coachList = response.data;
				});
				getDicts("puyu_classes").then(response => {
					this.puyuClassesOptions = response.data;
				});
				getDicts("puyu_stadium").then(response => {
					this.puyuStadiumOptions = response.data;
				});
			},
			handleCoachChange(coach) {
				this.form.userId = coach.userId;
				this.form.deptId = coach.deptId;
			},
			// 根据coachId获取教练姓名
			getCoachName(coachId) {
				if (this.coachList) {
					return this.coachList.filter(item => item.coachId == coachId)[0].coachName;
				}
				return '';
			},
			// 根据classesId获取班次
			getClassesName(classesId) {
				if (this.puyuClassesOptions) {
					return this.puyuClassesOptions.filter(item => item.dictValue == classesId)[0].dictLabel;
				}
				return '';
			},
			// 根据stadiumId获取场馆
			getStadiumName(stadiumId) {
				if (this.puyuStadiumOptions) {
					return this.puyuStadiumOptions.filter(item => item.dictValue == stadiumId)[0].dictLabel;
				}
				return '';
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					lessonId: null,
					userId: null,
					deptId: null,
					coachId: null,
					stadiumId: null,
					classesId: null,
					delFlag: null,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null,
					remark: null
				};
				this.resetForm("form");
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.lessonId)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset();
				this.open = true;
				this.title = "添加课时";
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				const lessonId = row.lessonId || this.ids
				getLesson(lessonId).then(response => {
					this.form = response.data;
					this.open = true;
					this.title = "修改课时";
				});
			},
			/** 提交按钮 */
			submitForm() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.form.lessonId != null) {
							updateLesson(this.form).then(response => {
								this.$modal.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							addLesson(this.form).then(response => {
								this.$modal.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const lessonIds = row.lessonId || this.ids;
				this.$modal.confirm('是否确认删除课时编号为"' + lessonIds + '"的数据项？').then(function() {
					return delLesson(lessonIds);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			/** 导出按钮操作 */
			handleExport() {
				this.download('puyu/lesson/export', {
					...this.queryParams
				}, `lesson_${new Date().getTime()}.xlsx`)
			},


			// 分页触发
			change(e) {
				this.$refs.table.clearSelection()
				this.ids.length = 0
				this.getData(e.current)
			},
			// 获取数据
			getData(pageCurrent, value = '') {
				this.queryParams.pageNum = pageCurrent
				this.getList()
			},
		}
	}
</script>

<style scoped>
	/* #ifndef H5 */
	/* page {
	padding-top: 85px;
} */
	/* #endif */
	.uni-group {
		display: flex;
		align-items: center;
	}

	.btn-rollcall {
		color: #ffffff;
		backgroundColor: #1AAD19;
		borderColor: #1AAD19
	}

	.page-sum {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.query-form {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-around;
		background-color: #ffffff;
		margin: 10px 0;
	}

	.query-item {
		/* width: 200px; */
		margin: 5px;
		padding: 5px;
	}
	
	.remark {
		color: #993399;
		font-weight: bolder;
	}
</style>